package site.hanzhe.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import site.hanzhe.constant.CrowdConstant;
import site.hanzhe.dao.AdminDao;
import site.hanzhe.entity.AdminEntity;
import site.hanzhe.exception.AdminAcctExistsException;
import site.hanzhe.exception.LoginFailedException;
import site.hanzhe.service.AdminService;
import site.hanzhe.utils.CrowdUtil;

import java.util.Date;
import java.util.List;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminDao adminDao;
    @Autowired
    private BCryptPasswordEncoder encoder;

    @Override
    public AdminEntity selectAdminByLoginAcct(AdminEntity entity) {
        // 如果有异常就会丢给Controller被全局异常处理器捕获，如果没有异常就正常返回
        entity = adminDao.selectOne(new QueryWrapper<AdminEntity>()
                .eq("ACCOUNT", entity.getAccount())
                .eq("PASSWORD", CrowdUtil.toMD5(entity.getPassword())));
        // 为null代表数据库中没有该用户，抛出登录异常
        if ( entity == null )
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        return entity;
    }

    @Override
    public AdminEntity selectAdminById(Integer id) {
        return adminDao.selectOne(new QueryWrapper<AdminEntity>().eq("id", id));
    }

    @Override
    public AdminEntity selectAdminByAccount(String account) {
        return adminDao.selectOne(new QueryWrapper<AdminEntity>().eq("ACCOUNT", account));
    }

    @Override
    public PageInfo<AdminEntity> selectAdminByQuery(Integer current, Integer size, String query) {
        // like为模糊查询，自动拼接%通配符，除了like之外还有notLike，likeLeft，likeRight
        PageHelper.startPage(current, size);
        List<AdminEntity> list = adminDao.selectList(new QueryWrapper<AdminEntity>()
                .select("ID", "ACCOUNT", "USERNAME", "EMAIL")
                .like("ACCOUNT", query)
                .or().like("USERNAME", query)
                .or().like("EMAIL", query)
                .orderByAsc("CREATE_TIME"));
        return new PageInfo<>(list, CrowdConstant.PAGE_NAVIGATE_LENGTH);
    }

    @Override
    public int deleteAdminById(Integer id) {
        return adminDao.deleteById(id);
    }

    @Override
    public int insertAdmin(AdminEntity entity) {
        // 插入到数据库之前先对实体类进行一些补充
        entity.setCreateTime(new Date());
        entity.setPassword( encoder.encode(entity.getPassword()) );
        int count = 0;
        try {
            // 处理账号重复时的解决方案
            count = adminDao.insert(entity);
        } catch (DuplicateKeyException e) {
            // 因为有很多地方都有可能抛出异常，为了提高细粒度在添加的位置单独声明一个异常
            throw new AdminAcctExistsException("该登录账号已存在，请更换后进行添加");
        }
        // 执行插入的逻辑
        return count;
    }

    @Override
    public int updateAdmin(AdminEntity entity) {
        // 针对密码做特殊处理，如果传来的值为空就设置为null，不为空就进行MD5加密
        String password = entity.getPassword();
        if ( password != null && password.trim().length() > 0 )
            entity.setPassword( CrowdUtil.toMD5(password) );
        else entity.setPassword(null);

        return adminDao.updateById(entity);
    }

    @Override
    public int deleteBatchByIds(List<Integer> adminIdList) {
        return adminDao.deleteBatchIds(adminIdList);
    }
}